#include <iostream>
using namespace std;
#include <vector>
#include <deque>

int process(vector<int>& arr , int num)
{
  deque<int> Max_Win(0 , 0);
  deque<int> Min_Win(0 , 0);

  int count = 0;
  int R = 0;
  int N = static_cast<int>(arr.size());
  for (int L = 0; L < N ; L++)
  {
    while (R < N)
    {
      while(!Max_Win.empty() && arr[Max_Win.back()] <= arr[R])
      {
        Max_Win.pop_back();
      }
      Max_Win.push_back(R);

      while(!Min_Win.empty() && arr[Min_Win.back()] >= arr[R])
      {
        Min_Win.pop_back();
      }
      Min_Win.push_back(R);

      if (arr[Max_Win.front()] - arr[Min_Win.front()] > num)
      {
        count += R - L;
        break;
      }
      else 
      {
        R++;
      }
        
    }

    if (Max_Win.front() == L)
    {
      Max_Win.pop_front();
    }

    if (Min_Win.front() == L)
    {
      Min_Win.pop_front();
    }
  }

  return count;
}











int main()
{
  vector<int> arr = {1 , 2 , 1};
  int ret = process(arr , 3);
  cout << ret << endl;
  return 0;
}
